{}
¶meals = {
'breakfast': 'oatmeal',
'lunch': 'leftovers',
'dinner': 'spaghetti'
}
NOTES
dict
type(meals)
meals
meals['breakfast']
NOTES
meals['lunch']
meals['leftovers']
NOTES
KeyError
for meal, offering in meals.items():
print(f'For {meal} you get {offering}. 😋')
for meal in meals: # iterate over keys
print(meal)
for dish in meals.values(): # iterate over values
print(dish)
NOTES
meals.items()
returns a sequence of key-value pairs, which we unpack into meal
and offering
list(meals.items())
in
¶significance = {
7: 'prime',
2: 'even prime',
3: 'prime',
5: 'prime',
9: 'even square',
4: 'even square',
1: 'multiplicative identity'
}
NOTES
7 in significance
8 in significance
for number in range(10):
if number in significance:
print(f'{number} is {significance[number]}.')
else:
print(f"I don't know anything special about {number}.")
NOTES
KeyError
key in dict
syntax to check that the key is presentYou are given a dictionary mapping words to emojis.
Replace all instances of a word with it's corresponding emoji. Ignore case.
So, given a dictionary
emojis = {'dog': '🐶', 'cat': '🐱', 'tree': '🌳', 'bird': '🐦'}
The phrase
My dog has fleas.
Becomes
My 🐶 has fleas.
def add_emojis(text, emojis):
"""Replace words in `emojis` with their corresponding symbols."""
words = text.split()
new_words = []
for word in words:
if word.lower() in emojis:
# replace
new_words.append(emojis[word.lower()])
else:
# don't replace
new_words.append(word)
return ' '.join(new_words)
def add_emojis(text, emojis):
new_words = []
for word in text.split():
if word in emojis:
word = emojis[word]
new_words.append(word)
return " ".join(new_words)
emojis = {
'dog': '🐶', # This one will get overwritten
'dog': '🐕',
'puppy': '🐶',
'dogs': '🐶🐶',
'cat': '🐱',
'tree': '🌳',
'bird': '🐦'
}
add_emojis("The Dogs chased the cat which chased the bird that sat in the tree in my yard.", emojis)
Community members want to register for the Rec Center sports teams.
You have a dictionary that maps age groups to team names.
Map a list of tuples containing a name and age to a list of tuples containing name and team.
To compute a participants age group, find the nearest multiple of 3 that is less than or equal to the participant age.
If the participant does not have an age-group assignment, they go in team "Adult League".
age_groups = {
0: 'Team Toddlers',
3: 'Tiny Troupers',
6: 'Starting Stars',
9: 'Mighty Middles',
12: 'Too Cool',
15: 'Boundless'
}
participants = [
('Joe', 14),
('Jane', 6),
('Johnny', 4),
('Jennifer', 20),
('Jack', 16),
('Janice', 2)
]
def assign_teams(partipants, age_groups):
"""Return a list of (person, team) tuples"""
teams = []
for name, age in participants:
# Find the age group (round down to nearest x3)
age_group = (age // 3) * 3
# Look up the team name
if age_group in age_groups:
your_team = age_groups[age_group]
else:
your_team = 'Adult League'
teams.append((name, your_team))
return teams
def assign_teams(participants, age_groups):
"""Returns a list of tuples of name and team."""
def assign_teams(participants, age_groups):
result = []
for name, age in participants:
age_group = (age // 3) * 3
group = age_groups.get(age_group, "Adult League")
result.append((name, group))
return result
assign_teams(participants, age_groups)
Given a dictionary mapping letters to other letters (called a "codex"), encode a message.
The codex only contains lower-case letters, but you should encode upper-case letters also. Preserve casing.
codex = {
'a': 'd',
'b': 'e',
'c': 'z',
'd': 'h',
'e': 'g',
'f': 's',
'g': 'n',
'h': 'r',
'i': 'a',
'j': 'b',
'k': 'k',
'l': 'j',
'm': 'c',
'n': 'u',
'o': 'y',
'p': 't',
'q': 'q',
'r': 'x',
's': 'w',
't': 'v',
'u': 'p',
'v': 'f',
'w': 'i',
'x': 'l',
'y': 'm',
'z': 'o'
}
def encode(codex, message):
"""Return the encoded message using the codex to map letters."""
encoded = ''
for char in message:
is_cap = char.isupper()
if char.lower() in codex:
char = codex[char.lower()]
if is_cap:
char = char.upper()
encoded += char
return encoded
def encode(codex, message):
result = ""
for char in message:
new_char = char
if char.lower() in codex:
new_char = codex[char.lower()]
if char.isupper():
new_char = new_char.upper()
result += new_char
return result
encode(codex, 'I like fish.')
dict
{}
key in dict
[]